// pages/posts/post-detail/post-detail.js
var postDatas = require("../../../data/posts-data.js");
var app = getApp();
Page({
  data: {

  },
  onLoad: function (options) {
    //获取列表传过来的id
    var postId = options.id;
    //根据id获取对应的详情
    var postData = postDatas.postList[postId];

    //根据id获取对应的缓存
    var collection = wx.getStorageSync('collection_' + postId);

    //设置数据
    this.setData({ collection: collection });
    this.setData({ id: postId });
    this.setData({ post: postData });

    // this.setData({isMusicPlaying:app.globalDatas.isPlayingMusic});
    this.addStateCallbacks();
  },
  onUnload:function(){
    if(this.data.isMusicPlaying){
         wx.stopBackgroundAudio();
    }  

    // app.globalDatas.isPlayingMusic = this.data.isMusicPlaying;
  },
  addStateCallbacks: function () {
    var that = this;
    wx.onBackgroundAudioPlay(function () {
      that.setData({ isMusicPlaying: true });
    });
    wx.onBackgroundAudioPause(function () {
      that.setData({ isMusicPlaying: false });
    });
    wx.onBackgroundAudioStop(function () {
      that.setData({ isMusicPlaying: false });
    })
  },
  onCollectionPost: function (event) {
    var collection = !event.currentTarget.dataset.collection;
    this.setData({ collection: collection });
    wx.setStorageSync("collection_" + this.data.id, collection);

    wx.showToast({
      title: collection ? "收藏成功" : "取消收藏"
    });
  },
  onSharePost: function (event) {
    var itemList = [
      "朋友圈", "微博"
    ];

    wx.showActionSheet({
      itemList: itemList,
      itemColor: "#000",
      success: function (res) {
        var item = itemList[res.tapIndex];
        wx.showToast({
          title: !res.cancel ? "分享到 " + item + " 成功" : "取消分享"
        });
      },
      fail: function () {
        wx.showToast({
          title: "分享失败"
        });
      },
    });
  },
  onMusicTap: function () {
    var isMusicPlaying = this.data.isMusicPlaying;
    var music = postDatas.postList[this.data.id].music;
    if (isMusicPlaying) {
      //正在播放，需要暂停
      wx.pauseBackgroundAudio();
    } else {
      //暂停播放，需要播放
      wx.playBackgroundAudio({
        dataUrl: music.url,
        title: music.title,
        coverImgUrl: music.coverImg
      });
    }

    //取反复制
    this.setData({ isMusicPlaying: !isMusicPlaying });
  },
  startMusic: function () {

  },
  pauseMusic: function () {
  }
})